package com;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.dataModel.Ayah;
import com.dataModel.Quran;
import com.dataModel.Sourah;

public class QuranParser {
	
	private static Quran quranModel=new Quran();
	private static Document doc;
	
	public static Quran getQuran()
	{
		return quranModel; 
	}
static
{
	try
	{
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    dbfactory.setNamespaceAware(true);
    DocumentBuilder domparser = dbfactory.newDocumentBuilder();

    //parse the XML and create the DOM
     doc = domparser.parse( QuranParser.class.getResourceAsStream("/com/data/quran.ar.xml"));

    process();
	}catch (Exception e) {
		e.printStackTrace();
	}
	
}

private static void process()
{
	 Element quran=doc.getDocumentElement();
	NodeList suras= quran.getElementsByTagName("sura");

	 //System.out.println(suras.getLength());
	 
	 
	
	 for(int i=0;i<Quran.SOWAR_NUMBER;i++)
	 {
		Node surah= suras.item(i);
		
		NamedNodeMap surahAttributes =surah.getAttributes();
		
		
		String sourahId= surahAttributes.item(0).getNodeValue();
		String sourahName= surahAttributes.item(1).getNodeValue();
		
		quranModel.getSowar()[i]=new Sourah(Integer.parseInt(sourahId),sourahName);
		
		NodeList ayat=((Element)surah).getElementsByTagName("aya");
		
		
		 for(int j=0;j<ayat.getLength();j++)
		 {
			 Element ayah=(Element)ayat.item(j);
			 String ayahId=ayah.getAttribute("id");
			Element searchTextElement=(Element) ayah.getElementsByTagName("searchtext").item(0);
			String searchText=searchTextElement.getChildNodes().item(0).getNodeValue();
			
			Element quranTextElement=(Element) ayah.getElementsByTagName("qurantext").item(0);
			String quranText=quranTextElement.getChildNodes().item(0).getNodeValue().trim();
			
			quranModel.getSowar()[i].getAyat().add(new Ayah(Integer.parseInt(ayahId),searchText,quranText));
			
			//System.out.println(ayahId+" : "+quranText);
	 
		 }
	 }
	 
	 quranModel.initSowar();

	
	

	
}

}
 